<template>
    <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" v-loading="formLoading">
        <el-form-item label="口味类别" prop="name">
            <el-input v-model="form.name" clearable />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submit" :loading="loading">确定</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts" name="AddOrEditTaste">
import { ref, reactive, onMounted } from 'vue';
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus';
import { tasteCreateOrEdit, tasteGetById } from '@/api/wx/taste';
import type { TasteType } from '@/api/wx/taste/types';

const props = defineProps(['isEdit', 'id'])
const emit = defineEmits(['success'])

const loading = ref(false)
const formLoading = ref(false)
let form = reactive<TasteType>({ name: '' })
const formRef = ref<FormInstance>()

// 校验规则
const rules = reactive<FormRules<TasteType>>({
    name: [{ required: true, message: '请输入口味类别', trigger: 'blur' }],
})

onMounted(() => {
    if (props.isEdit) {
        loadTaste()
    }
})

const loadTaste = async () => {
    formLoading.value = true
    const data = await tasteGetById(props.id)
    Object.assign(form, data.data)
    formLoading.value = false
}

const submit = async () => {
    await formRef.value?.validate()
    try {
        loading.value = true
        const data = await tasteCreateOrEdit(form)
        if (data.code === 200) {
            ElMessage.success(props.isEdit ? '修改成功' : '添加成功')
            emit('success')
        }
    } finally {
        loading.value = false
    }
}
</script>

<style scoped lang="scss"></style>